
export const formTime = (time) => {
    let d;
    if(Number(time)){
        d = new Date(Number(time))
    }else{
        d = new Date(time)
    }

    let arr = [
        d.getFullYear(),
        d.getMonth() + 1,
        d.getDate(),
        d.getHours(),
        d.getMinutes()
    ]
    arr = arr.map(item => {
        if(item < 10) {
            item = '0' + item
        }
        return item
    })
    return `${arr[0]}.${arr[1]}.${arr[2]} ${arr[3]}:${arr[4]}`
}

export const getQueryString = (field) => {
    const reg = new RegExp("(^|&)" + field + "=([^&]*)(&|$)", "i");
    const urlObj=window.location;
    var r =urlObj.href.indexOf('#')>-1? urlObj.hash.split("?")[1].match(reg) : urlObj.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

// 构建树形数据
export const buildTree = (list) => {
    let temp = {};
    let tree = [];
    for(var i=0; i < list.length; i++){
        temp[list[i].id] = list[i];
    }
    for(let i in temp){
        if(temp[i].parentId && temp[i].parentId != null && temp[temp[i].parentId]) {
            if(!temp[temp[i].parentId].son) {
                temp[temp[i].parentId].son = [];
            }
            temp[temp[i].parentId].son.push(temp[i]);
        } else {
            tree.push(temp[i]);
        }
    }
    return tree;
}

// 解析url中的query
export const urlParam = () => {
    let result = {};
    let urlArr = window.location.href.split('?')[1]
    if (!urlArr) return result;

    urlArr = urlArr.split('&')
    urlArr.map((item, index) => {
        let data = item.split('=')
        result[data[0]] = data[1]
    })

    return result;
}

// JSON的处理
export const JSONParse = jstr => {
    try {
        return JSON.parse(jstr)
    } catch (err) {
        return ''
    }
}

export const JSONStringify = jstr => {
    try {
        return JSON.stringify(jstr)
    } catch (err) {
        return ''
    }
}

// 请求数据处理
export const httpDataCommon = res =>{
    let {status, data} = res;
    let {code, message} = data;
    if (status != 200 && status != 304 && status != "0") {
        return
    }
    if (code == "0" && data.data) {
        return data.data;
    } else {
        return data;
    }
}

// 错误处理

export const handleCodeInfo = (data, callback) => {
    if(callback) {
        callback()
    }
    if (!data) {
        $.alert($i18n('cap.template.unflow.serverError'))
        return
    }else {
        const { message } = data || {}
        let errmessage = message || ""
        $.alert($i18n(errmessage))
    }
}